package com.bootssm.controller;

import com.bootssm.pojo.Book;
import com.bootssm.pojo.BookVO;
import com.bootssm.pojo.PageView;
import com.bootssm.pojo.Result;
import com.bootssm.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;

    @PostMapping("/findAll")
    public PageView<Book> findAll(@RequestBody BookVO bookVO) {
        Integer page = bookVO.getPage();
        Integer start = (page - 1) * bookVO.getSize();
        bookVO.setStart(start);
        List<Book> bookList = bookService.findAll(bookVO);
        Integer count = bookService.getCount(bookVO);
        PageView<Book> pageView = new PageView<>();
        pageView.setDataList(bookList);
        pageView.setCount(count);
        return pageView;
    }

    @PostMapping("/save")
    public Result save(@RequestBody Book book) {
        try {
            bookService.save(book);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "保存失败");
        }
        //保存数据库
        return new Result("200", "保存成功");
    }

    @GetMapping("/delete/{bookId}")
    public Result deleteId(@PathVariable("bookId") String bookId) {
        try {
            bookService.delete(bookId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "删除失败");
        }
        //保存数据库
        return new Result("200", "删除成功");
    }

    @GetMapping("/findById/{bookId}")
    public Book findById(@PathVariable("bookId") String bookId) {
        Book book = bookService.findById(bookId);
        return book;
    }

    @PostMapping("/update")
    public Result update(@RequestBody Book book) {
        try {
            bookService.update(book);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "修改失败");
        }
        //保存数据库
        return new Result("200", "修改成功");
    }
}
